package de.lulusoft.anothertorrent.core.xmlrpc;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;

public class XmlrpcSocketManager extends ConnectionManager {
	
	private XmlRpcSocketClientConfig config = null;
	private XmlRpcClient client = null;
	private final String m_host;
	private final int m_port;

	public XmlrpcSocketManager(String host, int port, boolean i8Support) throws XmlRpcException
	{	
		m_host = host;
		m_port = port;
		m_I8Support = i8Support;
	}

	@Override
	public void connect() throws XmlRpcException
	{		
		config = new XmlRpcSocketClientConfig();
		config.setHost(m_host);
		config.setPort(m_port);
		m_connected = true;

	    client = new XmlRpcClient();
	    client.setConfig(config);
	    client.setTypeFactory(new RTorrentTypeFactory(client, m_I8Support));
	    client.setTransportFactory(new XmlRpcSocketTransportFactory(client));
	}
	
	@Override
	public void disconnect()
	{
		super.disconnect();
	}
	
	@Override
	public Object sendSimpleCommand(String cmd) throws XmlRpcException
	{
		if (!m_connected)
			throw new XmlRpcException(ERROR_NOT_CONNECTED);
		
		Object[] params = new Object[]{};
		Object result = null;
		result = client.execute(cmd, params);
		return result;
	}
	
	@Override
	public Object sendCommand(String cmd, Object[] params) throws XmlRpcException
	{
		if (!m_connected)
			throw new XmlRpcException(ERROR_NOT_CONNECTED);
		Object result = null;
		result = client.execute(cmd, params);
		return result;
	}
}
